<template>
  <div>
    <kendoForm
      :kendo-form-items="kendoFormItems"
      :kendo-form="kendoForm"
      :kendo-params-value="kendoParamsValue"
    />
    <el-container v-if="tableGridView" style="padding-left:5px">
      <el-main>
        <KendoGridCmpt
          :ref="'PrjMemberExtraWorkKendoGrid'"
          :table-grid-option="tableGridOption"
          :table-grid-data-source-option="tableGridDataSourceOption"
          :table-grid-toolbar="tableGridToolbar"
        />
      </el-main>
    </el-container>
  </div>
</template>
<script>
  import kendoForm from '@/Views/components/kendo-vue-component/kendoForm/index.vue'
  import { isEmpty } from '@/Utils/strUtil.js'
  import moment from 'moment'
  export default {
    name: 'PrjOperateCmpt',
    components: {
      kendoForm
    },
    data() {
      return {
        dialogName: this.$attrs.data.dialogName,
        kendoFormItems: [
          {
            ref: 'PRJ_CD',
            remoteData: true,
            cascade: true,
            name: 'relPrjNo',
            label: '关联项目名称',
            paramName: 'relPrjNo',
            optionLabel: '--请选择--',
            controlType: 'dropDownList',
            required: true,
            filter: 'contains',
            dataType: 'json',
            transportReadUrl: '/service/prjMng/prjTransDict',
            autoBind: true,
            schema: {
              data: function(response) {
                if (typeof response.data === 'object') {
                  if (JSON.stringify(response.data) === '{}') {
                    return []
                  }
                }
                return response.data
              }
            },
            dataMapping: {
              label: 'dictValNm',
              value: 'dictVal'
            },
            parameterMap: function(options, operation) {
              if (operation !== 'read' && options.models) {
                // eslint-disable-next-line no-undef
                return { models: kendo.stringify(options.models) }
              } else {
                // eslint-disable-next-line no-undef
                return kendo.stringify({ dict: 'PRJ_CD' })
              }
            }
          },
          {
            id: 'memberNo',
            name: 'memberNo',
            label: '项目成员',
            paramName: 'memberNo',
            required: true,
            viewDisabled: true,
            controlType: 'multicolumncombobox',
            // change: this.devInChargeChange,
            dataSource: 'PrjMemberDataSource',
            dataType: 'json',
            transportReadUrl: '/service/prjMng/prjMemberMng/findPrjMemberList',
            dataMapping: {
              label: 'memberName',
              value: 'memberNo'
            },
            schema: {
              data: function(response) {
                if (typeof response.data === 'object') {
                  if (JSON.stringify(response.data) === '{}') {
                    return []
                  }
                }
                return response.data
              }
            },
            column: [
              {
                field: 'relPrjNo',
                title: '所属项目',
                width: 180
              },
              {
                field: 'memberNo',
                title: '项目成员编号',
                width: 120
              },
              {
                field: 'memberName',
                title: '项目成员名称',
                width: 120
              }
            ]
          },
          {
            name: 'performReqNo',
            label: '当前执行需求',
            paramName: 'performReqNo',
            required: true,
            controlType: 'multiselect',
            autoBind: false,
            remoteData: true,
            // change: this.devInChargeChange,
            dataSource: 'PrjReqTaskDataSource',
            dataType: 'json',
            transportReadUrl: '/service/prjMng/reqmntTaskMng/findReqMntTaskList',
            dataMapping: {
              label: 'reqName',
              value: 'reqNo'
            },
            schema: {
              data: function(response) {
                if (typeof response.data === 'object') {
                  if (JSON.stringify(response.data) === '{}') {
                    return []
                  }
                }
                return response.data
              }
            }
          },
          {
            name: 'vacateApplyDt',
            label: '申请日期',
            paramName: 'vacateApplyDt',
            controlType: 'datePicker',
            format: 'yyyy-MM-dd',
            viewDisabled: true,
            required: true
          },
          {
            name: 'vacateStartDt',
            label: '请假开始日期',
            paramName: 'vacateStartDt',
            controlType: 'datePicker',
            format: 'yyyy-MM-dd',
            viewDisabled: true,
            required: true,
            change: this.startChange
          },
          {
            name: 'vacateEndDt',
            label: '请假结束日期',
            paramName: 'vacateEndDt',
            controlType: 'datePicker',
            format: 'yyyy-MM-dd',
            viewDisabled: true,
            required: true,
            change: this.endChange
          },
          {
            ref: 'VACATE_DT_TYPE_CD',
            remoteData: true,
            cascade: true,
            name: 'vacateDtType',
            label: '请假类别',
            paramName: 'vacateDtType',
            optionLabel: '--请选择--',
            controlType: 'dropDownList',
            required: true,
            viewDisabled: true,
            filter: 'contains',
            dataType: 'json',
            transportReadUrl: '/service/sysMng/dict/findDictByTypeWithForm',
            autoBind: true,
            change: this.vacateDtTypeChange,
            schema: {
              data: function(response) {
                return response.data
              }
            },
            dataMapping: {
              label: 'dictValNm',
              value: 'dictVal'
            },
            parameterMap: function(options, operation) {
              if (operation !== 'read' && options.models) {
                // eslint-disable-next-line no-undef
                return { models: kendo.stringify(options.models) }
              } else {
                // eslint-disable-next-line no-undef
                return kendo.stringify({ dict: 'VACATE_DT_TYPE_CD' })
              }
            }
          },
          {
            name: 'vacateDays',
            label: '请假天数',
            paramName: 'vacateDays',
            controlType: 'numeric',
            disabled: true,
            viewDisabled: true,
            required: true
          },
          {
            ref: 'VACATE_TYPE_CD',
            remoteData: true,
            cascade: true,
            name: 'vacateType',
            label: '休假类型',
            paramName: 'vacateType',
            optionLabel: '--请选择--',
            controlType: 'dropDownList',
            required: true,
            filter: 'contains',
            dataType: 'json',
            transportReadUrl: '/service/sysMng/dict/findDictByTypeWithForm',
            autoBind: true,
            schema: {
              data: function(response) {
                return response.data
              }
            },
            dataMapping: {
              label: 'dictValNm',
              value: 'dictVal'
            },
            parameterMap: function(options, operation) {
              if (operation !== 'read' && options.models) {
                // eslint-disable-next-line no-undef
                return { models: kendo.stringify(options.models) }
              } else {
                // eslint-disable-next-line no-undef
                return kendo.stringify({ dict: 'VACATE_TYPE_CD' })
              }
            },
            change: this.vacateTypeChange

          },
          {
            name: 'vacateSignatory',
            label: '签字人',
            paramName: 'vacateSignatory',
            controlType: 'input',
            required: true
          },
          {
            genre: 'special',
            name: 'vacateReas',
            label: '请假原因',
            paramName: 'vacateReas',
            required: true,
            controlType: 'textarea'
          },
          {
            genre: 'special',
            name: 'vacatePeriod',
            label: '请假期间工作安排',
            paramName: 'vacatePeriod',
            required: true,
            controlType: 'textarea'
          }
        ],
        kendoForm: {
          ref: 'prodForm',
          valid: 'valid',
          buttons: [
            {
              name: '保存', // 按钮内容
              class: 'k-primary', // 按钮样式
              icon: 'save',
              click: this.save
            },
            {
              name: '重置', // 按钮内容
              icon: 'reset-sm',
              click: this.reset
            }
          ]
        },
        kendoParamsValue: {
          id: '',
          relPrjNo: '',
          memberNo: '',
          performReqNo: '',
          vacateApplyDt: this.dateFormat(new Date(), 'yyyy-MM-dd'),
          vacateStartDt: '',
          vacateEndDt: '',
          vacateDays: '',
          vacateType: '',
          vacateSignatory: '',
          vacateReas: '',
          vacatePeriod: '',
          usedExtraWorkDt: ''
        },
        /* Grid*/
        tableGridToolbar: [],
        tableGridParameterMap: {},
        tableGridView: false,
        tableGridOption: {
          ref: 'PrjMemberExtraWorkKendoGrid',
          dataSourceRef: 'prjMemberExtraWorkDataSource',
          remoteData: true,
          sortable: true,
          reorderable: true,
          resizable: true,
          pageable: true,
          selectSingle: true,
          selectMultiple: false,
          editable: 'inline',
          excel: {
            fileName: '成员加班记录明细',
            allPages: true,
            filterable: true
          },
          columns: [
            {
              field: 'memberNo',
              title: '开发人员',
              dictData: 'MEMBER_NO_CD',
              width: 120
            },
            {
              field: 'reqName',
              title: '需求/项目名称',
              width: 220
            },
            {
              field: 'reqTaskExecutor',
              title: '技术负责人',
              width: 120
            },
            {
              field: 'registrationDt',
              title: '登记日期',
              width: 120
            },
            {
              field: 'extraWorkDt',
              title: '加班日期',
              width: 120
            },
            {
              field: 'extraWorkStartTime',
              title: '加班开始时间',
              width: 170
            },
            {
              field: 'extraWorkEndTime',
              title: '加班结束时间',
              width: 170
            },
            {
              field: 'extraWorkDuration',
              title: '加班时长（小时）',
              width: 130
            },
            {
              field: 'extraWorkDays',
              title: '加班计入可调休天数',
              width: 150
            },
            {
              field: 'usedExtraWorkDays',
              title: '已使用加班天数',
              width: 120
            },
            {
              field: 'toBeUsedExtraWorkDays',
              title: '本次使用加班天数',
              width: 120,
              editor: this.toBeUsedExtraWorkDays
            },
            {
              field: 'whetherUsed',
              title: '是否已调休',
              width: 90,
              dictData: 'YES_OR_NO'
            }
          ]
        },
        tableGridDataSourceOption: {
          ref: 'dictDataSource',
          type: 'json',
          pageSize: 10,
          transportReadUrl: '/service/prjMng/prjMemberMng/findPrjMemberExtraWorkPage',
          transportUpdateUrl: '/service/prjMng/prjMemberMng/toBeUsedExtraWorkDaysUpdate',
          serverPaging: true,
          dict: ['DICT_STATUS_CD', 'YES_OR_NO'],
          remoteTransData: {
            REL_PRJ_CD: {
              transportName: 'prjInfoMngServiceImpl',
              transportMethod: 'prjTransDict',
              transportParam: {}
            },
            MEMBER_NO_CD: {
              transportName: 'prjMemberMngServiceImpl',
              transportMethod: 'prjMemberTransDict',
              transportParam: {}
            }
          },
          params: {},
          schema: {
            model: {
              id: 'id',
              fields: {
                relPrjNo: { editable: false, type: 'string' },
                reqName: { editable: false, type: 'string' },
                reqTaskExecutor: { editable: false, type: 'string' },
                registrationDt: { editable: false, type: 'string' },
                memberNo: { editable: false, type: 'string' },
                performReqNo: { editable: false, type: 'string' },
                extraWorkDt: { editable: false, type: 'string' },
                extraWorkStartTime: { editable: false, type: 'string' },
                extraWorkEndTime: { editable: false, type: 'string' },
                extraWorkDuration: { editable: false, type: 'string' },
                extraWorkDays: { editable: false, type: 'string' },
                whetherConfirmValidity: { editable: false, type: 'string' },
                whetherUsed: { editable: false, type: 'string' },
                paidLeaveDate: { editable: false, type: 'string' },
                extraWorkReas: { editable: false, type: 'string' },
                usedExtraWorkDays: { editable: false, type: 'string' },
                toBeUsedExtraWorkDays: { editable: true, type: 'string', defaultValue: '0' }

              }
            },
            data: function(response) {
              return response.data.list
            },
            total: function(response) {
              return response.data.total
            }
          },
          parameterMap: this.ExtraWorkGridParameterMap
        }
      }
    },
    mounted() {
      this.kendoParamsValue = Object.assign(this.kendoParamsValue, this.deepCopy(this.$attrs.data.param))
      const operatorType = this.$attrs.data.operatorType
      const { memberNo, usedExtraWorkDt, id } = this.kendoParamsValue
      let whetherUsed = ''
      let relVacateId = ''
      const usedExtraWorkDtItem = {
        id: 'usedExtraWorkDt',
        name: 'usedExtraWorkDt',
        label: '使用加班日期',
        genre: 'special',
        paramName: 'usedExtraWorkDt',
        required: true,
        controlType: 'multiselect',
        autoBind: true,
        remoteData: true,
        // change: this.devInChargeChange,
        dataSource: 'ExtraWorkDtDataSource',
        dataType: 'json',
        transportReadUrl: '/service/prjMng/prjMemberMng/findExtraWorkDtWithMember',
        dataMapping: {
          label: 'extraWorkDtDesc',
          value: 'extraWorkDt'
        },
        schema: {
          data: function(response) {
            if (typeof response.data === 'object') {
              if (JSON.stringify(response.data) === '{}') {
                return []
              }
            }
            return response.data
          }
        },
        parameterMap: function(options, operation) {
          if (operation !== 'read' && options.models) {
            // eslint-disable-next-line no-undef
            return { models: kendo.stringify(options.models) }
          } else {
            // eslint-disable-next-line no-undef
            return kendo.stringify({
              memberNo,
              whetherUsed: whetherUsed,
              relVacateId: relVacateId
            })
          }
        },
        change: this.usedExtraWorkDtChange
      }
      const { vacateType } = this.kendoParamsValue
      const index = this.kendoFormItems.map(s => s.name).indexOf('usedExtraWorkDt')
      if (vacateType === '05') {
        if (index < 0) {
          // const index_ = this.kendoFormItems.map(s => s.name).indexOf('vacateType')
          // const newKendoFormItems = []
          // this.kendoFormItems.forEach(element => {
          //   newKendoFormItems.push(element)
          //   if (element.paramName === 'vacateType') {
          //     newKendoFormItems.push(usedExtraWorkDt)
          //   }
          // })
          // this.kendoFormItems = newKendoFormItems
          this.kendoFormItems.push(usedExtraWorkDtItem)
        }
      } else {
        if (index > -1) {
          this.kendoFormItems.splice(index, 1)
        }
      }
      if (operatorType === 'view') {
        this.kendoFormItems.forEach(element => {
          if (!isEmpty(this.kendoParamsValue[element.paramName]) &&
            typeof this.kendoParamsValue[element.paramName] === 'string' &&
            this.kendoParamsValue[element.paramName].split(',').length > 1) {
            this.$set(this.kendoParamsValue, element.paramName, this.kendoParamsValue[element.paramName].split(','))
          }
          if (element.viewDisabled) {
            element.disabled = true
          }
        })
      } else if (operatorType === 'edit') {
        this.kendoFormItems.forEach(item => {
          // Array.isArray(this.kendoParamsValue[item.paramName])
          if (!isEmpty(this.kendoParamsValue[item.paramName]) &&
            typeof this.kendoParamsValue[item.paramName] === 'string' &&
            this.kendoParamsValue[item.paramName].split(',').length > 1) {
            this.$set(this.kendoParamsValue, item.paramName, this.kendoParamsValue[item.paramName].split(','))
          }
          if (item.editDisabled) {
            item['readonly'] = true
          }
        })
      }
      if (isEmpty(usedExtraWorkDt)) {
        whetherUsed = '2'
        this.tableGridView = false
      } else {
        const usedExtraWorkDtArr = usedExtraWorkDt.split(',')
        whetherUsed = '1'
        relVacateId = id
        // 根据使用的加班日期，读取加班日期详细信息明细。
        // 组装参数：
        const parameterMap = {}
        this.$set(parameterMap, 'memberNo', memberNo)
        this.$set(parameterMap, 'usedExtraWorkDt', usedExtraWorkDtArr)
        this.tableGridParameterMap = Object.assign(this.tableGridParameterMap, this.deepCopy(parameterMap))
        this.tableGridView = true
      }
    },
    methods: {
      startChange(e) {
        const StartDt = e.sender.value()
        const { vacateEndDt } = this.kendoParamsValue
        const EndDt = moment(vacateEndDt, 'YYYY-MM-DD')
        if (!isEmpty(vacateEndDt)) {
          const days = EndDt.diff(StartDt, 'day') + 1
          if (days > 1) {
            this.kendoFormItems.forEach(element => {
              if (element.paramName === 'vacateDtType') {
                element.disabled = true
              }
            })
            this.$set(this.kendoParamsValue, 'vacateDtType', '01')
            this.$set(this.kendoParamsValue, 'vacateDays', days)
          }
          if (days < 1) {
            this.$KendoNotify({
              title: '提示信息:',
              message: '当前开始日期不能大于结束日期'
            }, 'warning')
            e.sender.value('')
            this.$set(this.kendoParamsValue, 'vacateStartDt', '')
          }
        }
      },
      endChange(e) {
        const EndDt = moment(e.sender.value())
        const { vacateStartDt } = this.kendoParamsValue
        const StartDt = moment(vacateStartDt, 'YYYY-MM-DD')
        if (!isEmpty(vacateStartDt)) {
          const days = EndDt.diff(StartDt, 'day') + 1
          if (days > 1) {
            this.kendoFormItems.forEach(element => {
              if (element.paramName === 'vacateDtType') {
                element.disabled = true
              }
            })
            this.$set(this.kendoParamsValue, 'vacateDtType', '01')
            this.$set(this.kendoParamsValue, 'vacateDays', days)
          }
          if (days < 1) {
            this.$KendoNotify({
              title: '提示信息:',
              message: '当前结束日期不能小于开始日期'
            }, 'warning')
            e.sender.value('')
            this.$set(this.kendoParamsValue, 'vacateEndDt', '')
          }
        }
      },
      vacateDtTypeChange(e) {
        const vacateDtType = e.sender.value()
        const { vacateStartDt, vacateEndDt } = this.kendoParamsValue
        const StartDt = moment(vacateStartDt, 'YYYY-MM-DD')
        const EndDt = moment(vacateEndDt, 'YYYY-MM-DD')
        if (!isEmpty(vacateStartDt) && !isEmpty(vacateEndDt)) {
          if (vacateDtType === '01') {
            this.$set(this.kendoParamsValue, 'vacateDays', EndDt.diff(StartDt, 'day') + 1)
          } else {
            this.$set(this.kendoParamsValue, 'vacateDays', 0.5)
          }
        }
      },
      vacateTypeChange(e) {
        const { memberNo } = this.kendoParamsValue
        const usedExtraWorkDt = {
          id: 'usedExtraWorkDt',
          name: 'usedExtraWorkDt',
          genre: 'special',
          label: '使用加班日期',
          paramName: 'usedExtraWorkDt',
          required: true,
          controlType: 'multiselect',
          autoBind: true,
          remoteData: true,
          // change: this.devInChargeChange,
          dataSource: 'ExtraWorkDtDataSource',
          dataType: 'json',
          transportReadUrl: '/service/prjMng/prjMemberMng/findExtraWorkDtWithMember',
          dataMapping: {
            label: 'extraWorkDtDesc',
            value: 'extraWorkDt'
          },
          schema: {
            data: function(response) {
              if (typeof response.data === 'object') {
                if (JSON.stringify(response.data) === '{}') {
                  return []
                }
              }
              return response.data
            }
          },
          change: this.usedExtraWorkDtChange,
          parameterMap: function(options, operation) {
            if (operation !== 'read' && options.models) {
              // eslint-disable-next-line no-undef
              return { models: kendo.stringify(options.models) }
            } else {
              // eslint-disable-next-line no-undef
              return kendo.stringify({
                memberNo,
                whetherUsed: '2'
              })
            }
          }
        }
        const vacateType = e.sender.value()
        const index = this.kendoFormItems.map(s => s.name).indexOf('usedExtraWorkDt')
        if (vacateType === '05') {
          if (index < 0) {
            this.kendoFormItems.push(usedExtraWorkDt)
          }
        } else {
          if (index > -1) {
            this.kendoFormItems.splice(index, 1)
          }
        }
      },
      usedExtraWorkDtChange(e) {
        const valList = e.sender.value()
        if (valList.length > 0) {
          const { memberNo, usedExtraWorkDt } = this.kendoParamsValue
          // 根据使用的加班日期，读取加班日期详细信息明细。
          // 组装参数：
          const parameterMap = {}
          this.$set(parameterMap, 'memberNo', memberNo)
          this.$set(parameterMap, 'usedExtraWorkDt', usedExtraWorkDt)
          this.tableGridParameterMap = Object.assign(this.tableGridParameterMap, this.deepCopy(parameterMap))
          if (this.tableGridView) {
            this.$refs['PrjMemberExtraWorkKendoGrid'].transportReadGrid()
          } else {
            this.tableGridView = true
          }
        } else {
          this.tableGridView = false
        }
      },
      ExtraWorkGridParameterMap(options, operation) {
        if (operation !== 'read' && options) {
          // eslint-disable-next-line no-undef
          return kendo.stringify(options)
        } else {
          debugger
          const parameterMap = Object.assign({}, this.deepCopy(this.tableGridParameterMap))
          parameterMap.pageNum = options.page
          parameterMap.pageSize = options.pageSize
          // eslint-disable-next-line no-undef
          return kendo.stringify(parameterMap)
        }
      },
      toBeUsedExtraWorkDays(container, options) {
        const that_ = this
        // eslint-disable-next-line no-undef
        kendo.jQuery('<input required name="' + options.field + '"/>')
          .appendTo(container).kendoNumericTextBox({
            decimals: 2,
            min: 0,
            step: 0.5,
            restrictDecimals: false,
            culture: 'zh-CN',
            change: function(e) {
              const { usedExtraWorkDays, extraWorkDays } = options.model
              const toBeUsedExtraWorkDays = e.sender.value()
              if (toBeUsedExtraWorkDays > (parseFloat(extraWorkDays) - parseFloat(isEmpty(usedExtraWorkDays) ? '0' : usedExtraWorkDays))) {
                that_.$KendoNotify({
                  title: '提示信息:',
                  message: '此次使用加班天数已超出当前可使用的加班天数，请重新填写！'
                }, 'warning')
              }
            }
          })
      },
      toBeUsedExtraWorkDaysChange(e) {
        console.log(1)
      },
      save(paramVal, validator) {
        this.kendoFormItems.forEach(item => {
          if (Array.isArray(paramVal[item.paramName])) {
            this.$set(paramVal, item.paramName, paramVal[item.paramName].join(','))
          }
          if (item.viewDisabled) {
            item['disabled'] = true
          }
        })
        // 校验当前选择调休日期不能大于或等于请假日期

        if (validator.validate()) {
          this.$kendoConfirm({
            title: '提示消息',
            message: '请确认已经更新当前加班日期的可使用调休天数！',
            btn: [
              {
                type: 'submit',
                text: '确定'
              },
              {
                type: 'cancel',
                text: '取消'
              }
            ]
          }).then(_ => {
            // 执行submit方法
            this.$post('/service/prjMng/prjMemberMng/savePrjMemberVacate', paramVal).then(res => {
              if (res.code !== 200) {
                this.$KendoNotify({
                  title: '错误信息:' + res.code,
                  message: res.message
                }, 'error')
              } else {
                this.$KendoNotify({
                  title: '提示信息:',
                  message: res.message
                }, 'success')
                this.$bus.emit('dialog' + `${this.dialogName}`, true)
              }
            })
          }).catch(_ => {
            // 执行cancel方法
            this.$KendoNotify({
              title: '提示信息:',
              message: '取消保存！'
            }, 'warning')
          })
        }
      },
      reset(paramVal) {
        Object.keys(paramVal).forEach(key => {
          if (Array.isArray(paramVal[key])) {
            this.kendoParamsValue[key] = []
          } else {
            this.kendoParamsValue[key] = ''
          }
        })
      }
    }
  }
</script>

<style>

</style>
